package io.renren.common.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;


import io.renren.modules.work.dao.ScGoodsDao;
import io.renren.modules.work.entity.ExcelData_Goods;
import io.renren.modules.work.entity.ScGoodsEntity;
import io.renren.modules.work.service.ScGoodsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 给Listener创建成员变量，然后在构造方法里面传进去。必须不让spring管理Listener，每次读取    都要new一个。
 */
public class ExcelListener extends AnalysisEventListener<ExcelData_Goods> {


    private ScGoodsDao scGoodsDao;

    private static final Logger logger = LoggerFactory.getLogger(ExcelListener.class);
    private static final int BATCH_COUNT = 500;
    List<ScGoodsEntity> goodsList = new ArrayList<>(1000);

    public ExcelListener(ScGoodsDao scGoodsDao) {
        this.scGoodsDao = scGoodsDao;
    }


    @Override
    public void invoke(ExcelData_Goods excelData, AnalysisContext context) {
        ScGoodsEntity scGoodsEntity = new ScGoodsEntity();
        scGoodsEntity.setGoodsno(ConfigConstant.generateGoodsNo());
        scGoodsEntity.setGoodsname(excelData.getGoodsname());
        scGoodsEntity.setGoodsunit(excelData.getGoodsunit());
        scGoodsEntity.setGoodstype(excelData.getGoodstype());
        scGoodsEntity.setGoodsstate("1");
        goodsList.add(scGoodsEntity);
        if(goodsList.size()>=BATCH_COUNT){
            saveData();
        }
    }
    /**
     * 所有数据解析完成了会调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //将列表中剩余的数据也插入到数据库中
        if(!goodsList.isEmpty() ) {
            saveData();
        }
        logger.info("所有数据存储完成");
    }
    //数据库持久化操作
    void saveData() {
        scGoodsDao.batchInsert(goodsList);
        goodsList.clear();
    }
}

